﻿using System;
using System.Collections.Generic;
using UnityEngine;
using Interface;

namespace Client
{
    /// <summary>
    /// 界面基类：对应一个UIVisual
    /// </summary>
    public class UIWindow : UIBase
    {
        protected UIWindow(string uiKey) : base(uiKey)
        {
        }

        #region widget
        private List<UIWidget> m_AttachedWidgets;

        /// <summary>
        /// widget附加到本界面某个节点下了
        /// 使用者确保参数有效性
        /// </summary>
        /// <param name="widget"></param>
        public void OnWidgetAttached(UIWidget widget)
        {
            Log.Debug("UIWindow.OnWidgetAttached {0} {1}", UIKey, widget.UIKey);
            if (m_AttachedWidgets == null)
            {
                m_AttachedWidgets = new List<UIWidget> { widget };
            }
        }

        /// <summary>
        /// widget不再附加到本界面某个节点下了
        /// 使用者确保参数有效性
        /// </summary>
        /// <param name="widget"></param>
        public void OnWidgetDetached(UIWidget widget)
        {
            Log.Debug("UIWindow.OnWidgetDetached {0} {1}", UIKey, widget.UIKey);
            if (m_AttachedWidgets != null)
            {
                var index = m_AttachedWidgets.IndexOf(widget);
                if (index != -1)
                {
                    m_AttachedWidgets.RemoveAt(index);
                    return;
                }
            }
            Log.Error("UIWindow.OnWidgetDetached not attached {0} {1}", UIKey, widget.UIKey);
        }

        /// <summary>
        /// 断绝与Widget的关联
        /// </summary>
        private void DoDetachWidget()
        {
            if (m_AttachedWidgets != null)
            {
                for (int i = m_AttachedWidgets.Count - 1; i >= 0; --i)
                {
                    m_AttachedWidgets[i].DetachFromWindow();
                }
                m_AttachedWidgets.Clear();
            }
        }
        #endregion

        #region override
        protected override void OnVisualLoaded()
        {
            base.OnVisualLoaded();

            Log.Debug("UIWindow.OnVisualLoaded {0} InUsing[{1}]", UIKey, InUsing);

            if (!InUsing)
            {
                return;
            }
        }

        protected override void DoSafeClear()
        {
            Log.Debug("UIWindow.DoSafeClear {0}", UIKey);

            DoDetachWidget();

            base.DoSafeClear();
        }
        #endregion
    }
}
